<template>
  <ul class="list">
    <li
      class="item"
      v-for="item of letters"
      :key="item"
      :ref="item"
      @click="handleLetterClick"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @tuchend="handleTouchEnd"

    >
      {{item}}
    </li>
  </ul>
</template>

<script>
  export default {
    name: "CityAlphabet",
    data () {
      return {
        touchStatus: false,
        startY: 0,
        timer: null
      }
    },
    updated () {
      // 1.获取 A 字母距离顶部的高度用于计算字母表长按拖动
      this.startY = this.$refs['A'][0].offsetTop;
    },
    props: {
      cities: {
        type: Object
      }
    },
    computed: {
      letters () {
        const letters = [];
        for(let i in this.cities) {
          letters.push(i)
        }
        return letters
      }
    },
    methods: {
      handleLetterClick (e) {
        // console.log(e.target.innerText);
        this.$emit('change',e.target.innerText)
      },
      handleTouchStart () {
        this.touchStatus = true;
      },
      handleTouchMove (e) {
        if (this.touchStatus) {
          if (this.timer) {
            clearTimeout(this.timer)
          }
          this.timer = setTimeout( () => {
            // 1.A 字母距离顶部的高度 this.startY
            // 2.移动结束的位置 = 移动时距离顶部的位置 - （头部 + 搜索框 = 79);
            const touchY = e.touches[0].clientY - 79;
            // 3.计算滚动结束后所在字母的索引
            // 3.1当前所在字母的索引 = 移动结束的位置 - A字母距离顶部的位置 的插值 / 每个字母的高度约20
            const index = Math.floor((touchY - this.startY) / 20);
            if (index >= 0 && index < this.letters.length) {
              this.$emit('change', this.letters[index]);
            }
          },16)
        }
      },
      handleTouchEnd () {
        this.touchStatus = false
      }
    }
  }
</script>

<style scoped lang="stylus">
  @import '~styles/varibles.styl'
  .list
    display flex
    flex-direction column
    justify-content center
    position absolute
    top 1.58rem
    bottom 0
    right 0
    width .4rem
    .item
      text-align center
      line-height .4rem
      color $bgColor
</style>
